<?php

namespace BP\CompteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use BP\CompteBundle\Entity\Compte;
use BP\CompteBundle\Entity\Operation;
use BP\CompteBundle\Form\CompteType;
use BP\CompteBundle\Form\OperationType;

/**
 * Compte controller.
 *
 */
class CompteController extends Controller
{
	public function deleteOperationAction()
	{

	}

	/*
	*	Crée une operation a partir du formulaire present dans la page
	*	principale. Utilise uniquement la méthode POST
	*/
	public function createOperationAction()
	{
		$request = $this->container->get('request');

		$operation = new Operation();
		if ($request->isXmlHttpRequest()) {
			$compteId = $request->get('compteId');
			$operation->setCompteId($compteId);
		}	

		$form = $this->createForm(new OperationType(), $operation);			
		
		
		// lorsque le formulaire est envoyé
		if ( ($request->getMethod() == "POST") && (!$request->isXmlHttpRequest()) ) {
		
			$form->bindRequest($request);

			if ($form->isValid()) {
			
				$operation = $form->getData();
				$compteId = $operation->getCompteId();
				$typeOperation = $operation->getType();				

				// enregistrement de loperation en BD
				$em = $this->getDoctrine()->getEntityManager();
				$em->persist($operation);
				$em->flush();

				//Mise a jour du compte en BD
				$compte = $em->getRepository('BPCompteBundle:Compte')
							->find($compteId);
			
				// si le type est 1 cest une addition, sinon une soustraction
				if ( $typeOperation == 1 ) {
					$currentSolde = $compte->getSolde() + $operation->getValeur();
				} else {
					$currentSolde = $compte->getSolde() - $operation->getValeur();
				}

				$compte->setSolde($currentSolde);
				$em->persist($compte);
				$em->flush();

				return $this->redirect($this->generateUrl('BPCompteBundle_CompteManager_displayCompte', array('id' => $compteId)));

			} 
		} 
		
			return $this->container->get('templating')->renderResponse('BPCompteBundle:Compte:createOperation.html.twig', array('form' => $form->createView()) );
		
	}
}
